package com.utilviet.baovn.objects;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.JsonReader;
import android.util.Log;

import com.utilviet.baovn.Utility.Utility;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

/**
 * Created by phuongle on 7/8/15.
 */
public class DataBase {
    public static final String DEFAULT_JSON_DATA = "websites.json";
    public static final String FILE_FAVORITE_WEB_IDS = "favWebIds.dat";

    public static final String KEY_FAVORITE_WEBS = "favWebs";
    public static final String KEY_ORDERED = "ordered";
    public static final String KEY_ICON = "icon";

    public static final String KEY_MARKED = "marked";
    public static final String MARKED_VALUE = "1";
    public static final String UNMARKED_VALUE = "0";

    public static boolean loadDefault(Context context,
                                      ArrayList<String> favWebIds,
                                      ArrayList<HashMap<String, String>> favoriteWebsites,
                                      ArrayList<HashMap<String, String>> otherWebsites) {
        try {
            InputStream is = context.getAssets().open(DEFAULT_JSON_DATA);
            JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));

            reader.beginObject();

            while (reader.hasNext()) {
                String name = reader.nextName();

                if (name.equals("websites")) {
                    //
                    reader.beginArray();

                    while (reader.hasNext()) {
                        HashMap<String, String> website = new HashMap<String, String>();

                        //
                        reader.beginObject();

                        while (reader.hasNext()) {
                            String webKey = reader.nextName();
                            String webValue = reader.nextString();

                            if (webKey != null && webKey.length() > 0) {
                                website.put(webKey, webValue);
                            }
                        }

                        reader.endObject();

                        //
                        if (favWebIds != null) {
                            boolean isMarked = false;
                            int idx = 0;

                            if (favWebIds.size() > 0) {
                                String id = website.get("id");

                                for (idx = 0; idx < favWebIds.size(); idx ++) {
                                    String value = favWebIds.get(idx);
                                    if ( id.equals(value.trim()) ) {
                                        isMarked = true;

                                        break;
                                    }
                                }
                            }

                            if (isMarked) {
                                website.put(KEY_MARKED, MARKED_VALUE);
                                website.put(KEY_ORDERED, idx + "");

                                favoriteWebsites.add(website);
                            }
                            else {
                                website.put(KEY_MARKED, UNMARKED_VALUE);

                                otherWebsites.add(website);
                            }
                        }
                        else {
                            // Load favorite default
                            String marker = website.get(KEY_MARKED);

                            if (marker != null && marker.equals(MARKED_VALUE)) {
                                favoriteWebsites.add(website);
                            }
                            else {
                                otherWebsites.add(website);
                            }
                        }
                    }

                    reader.endArray();
                }
                else {
                    reader.skipValue();
                }
            }

            reader.endObject();
            reader.close();

            is.close();

            // Sort data
            if (favWebIds != null && favWebIds.size() > 0) {
                sortByKey(favoriteWebsites, KEY_ORDERED);
            }

            sortByKey(otherWebsites, KEY_ICON);
        }
        catch (Exception e) {
            e.printStackTrace();

            return false;
        }

        return true;
    }

    public static void sortByKey(ArrayList<HashMap<String, String>> list, final String key) {
        Collections.sort(list, new Comparator< HashMap<String, String> >() {

            @Override
            public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
                String left = lhs.get(key);
                String right = rhs.get(key);

                return left.compareTo(right);
            }
        });
    }

    public static ArrayList<String> loadFile(String fileName) {
        try {
            String filePath = Utility.getAppFolder() + File.separator + fileName;

            //
            File file = new File(filePath);

            if (file.exists() == false) {
                return null;
            }

            //
            FileInputStream fis = new FileInputStream(file);

            ObjectInputStream ois = new ObjectInputStream(fis);
            ArrayList<String> favoriteWebsites = (ArrayList<String>) ois.readObject();
            ois.close();

            fis.close();

            return favoriteWebsites;
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static ArrayList<String> loadRef(Context context) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

        //
        String valueString = settings.getString(KEY_FAVORITE_WEBS, null);
        if (valueString == null) {
            return null;
        }

        ArrayList<String> array = new ArrayList<String>(Arrays.asList(valueString.split(",")));

        return array;
    }

    public static boolean saveFile(ArrayList<String> favoriteWebsites, String fileName) {
        //
        try {
            String filePath = Utility.getAppFolder() + File.separator + fileName;

            FileOutputStream fos = new FileOutputStream(filePath);

            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(favoriteWebsites);
            oos.close();

            fos.close();
        }
        catch (Exception e) {
            e.printStackTrace();

            return false;
        }

        return true;
    }

    public static boolean saveRef(Context context, ArrayList<String> favoriteWebsites) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

        SharedPreferences.Editor editor = settings.edit();

        StringBuilder favWebs = new StringBuilder("");
        for (String id : favoriteWebsites) {
            favWebs.append(id + ",");
        }

        String webs = favWebs.toString();

        String websTmp = "";

        if (webs != null && webs.length() > 0) {
            websTmp = webs.substring(0, webs.length() - 1);
        }

        editor.putString(KEY_FAVORITE_WEBS, websTmp);

        editor.commit();

        return true;
    }
}
